package com.yonyou.pmclouds.plan.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.consts.MillStoneStatusConst;
import com.yonyou.pmclouds.basecom.consts.PlanProgressHisConst;
import com.yonyou.pmclouds.basecom.consts.PlanProgressMarkConst;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.IllegalRequestArgException;
import com.yonyou.pmclouds.basecom.util.SqlUtil;
import com.yonyou.pmclouds.businessobject.util.BulkDataSplitUtils;
import com.yonyou.pmclouds.externalservice.entity.FailedExternalRecordVO;
import com.yonyou.pmclouds.externalservice.rmiitf.FailedExternalRecordQuery;
import com.yonyou.pmclouds.measureindex.entity.MeasureIndexHistoryVO;
import com.yonyou.pmclouds.measureindex.mapper.MeasureIndexHisMapper;
import com.yonyou.pmclouds.measureindex.service.rmiitf.MeasureIndexHisQuery;
import com.yonyou.pmclouds.milestone.service.IBillTypeRefService;
import com.yonyou.pmclouds.milestone.service.IMilestoneQuery;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.plan.entity.*;
import com.yonyou.pmclouds.plan.mapper.PlanProgressHistoryMapper;
import com.yonyou.pmclouds.plan.mapper.PlanProgressMapper;
import com.yonyou.pmclouds.plan.mapper.PlanWriteMapper;
import com.yonyou.pmclouds.plan.mapper.ProjectPlanMapper;
import com.yonyou.pmclouds.plan.plandriven.rmiitf.IPlanDepartmemtQuery;
import com.yonyou.pmclouds.plan.planindex.entity.PlanIndexVO;
import com.yonyou.pmclouds.plan.planindex.rmiitf.IPlanIndexQuery;
import com.yonyou.pmclouds.plan.rmiitf.ProjectPlanQuery;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.mapper.ProjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Deprecated
@Service(version = ApplicationConsts.APPLICATION_VERSION, interfaceClass = ProjectPlanQuery.class, timeout = 3000)
public class ProjectPlanQueryImpl implements ProjectPlanQuery {

    @Autowired
    private ProjectPlanMapper mapper;
    @Autowired
    private PlanProgressMapper progMapper;
    @Autowired
    private PlanProgressHistoryMapper hisMapper;
    @Autowired
    private PictureRemoteService picService;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private FailedExternalRecordQuery recordQuery;
    @Autowired
    private PlanWriteMapper planWriteMapper;
    @Autowired
    private IMilestoneQuery milestoneQuery;
    @Autowired
    private MeasureIndexHisQuery measureIndexHisQuery;
    @Autowired
    private MeasureIndexHisMapper measureIndexHisMapper;
    @Autowired
    private IBillTypeRefService billTypeRefService;
    @Autowired
    private IPlanIndexQuery planIndexQuery;
    @Autowired
    private IPlanDepartmemtQuery departmemtQuery;






    @Override
    public ProjectPlanVO[] queryPlanByProject(String projectId) throws BusinessException {
        if (projectId == null) {
            throw new IllegalRequestArgException();
        }
        return mapper.queryProjectPlan(projectId);
    }

    @Override
    public ProjectPlanVO[] queryPlanByRoot(String rootId) throws BusinessException {
        if (rootId == null) {
            throw new IllegalRequestArgException();
        }
        return mapper.queryPlanByRoot(rootId);
    }

    @Override
    public ProjectPlanViewVO[] queryViewByRoot(String rootId) throws BusinessException {
        ProjectPlanVO[] allPlans = this.queryPlanByRoot(rootId);
        if (ArrayUtils.isEmpty(allPlans)) {
            return null;
        }
        ProjectPlanViewVO[] plans = transAndFillViewVO(allPlans);
        return plans;
    }

    @Override
    public ProjectPlanVO queryPlanById(String planId) throws BusinessException {
        if (planId == null) {
            throw new IllegalRequestArgException();
        }
        return mapper.getById(planId);
    }

    @Override
    public ProjectPlanVO queryPlanByIdWithPic(String planId) throws BusinessException {
        ProjectPlanVO plan = this.queryPlanById(planId);
        String[] pics = picService.queryPicNamesByPkEntity(planId);
        if (pics != null) {
            plan.setPictures(pics);
        } else {
            plan.setPictures(new String[0]);
        }
        return plan;
    }

    @Override
    public PlanProgressVO queryProgress(String planId) {
        return progMapper.getById(planId);
    }

    @Override
    public ProjectPlanVO[] queryLeafByRoot(String rootId) throws BusinessException {
        if (rootId == null) {
            throw new IllegalRequestArgException();
        }
        return mapper.queryLeafByRoot(rootId);
    }

    @Override
    public ProjectPlanViewVO[] queryViewByProject(String projectId) throws BusinessException {
        ProjectPlanVO[] allPlans = this.queryPlanByProject(projectId);
        if (ArrayUtils.isEmpty(allPlans)) {
            return null;
        }
        //检验项目下根计划是否是审批中
        checkRootPlan(allPlans);
        ProjectPlanViewVO[] plans = transAndFillViewVO(allPlans);
        return plans;
    }

    private void checkRootPlan(ProjectPlanVO[] projectPlanVOS) {
        Set<String> pkPlans = new HashSet<>();
        for (ProjectPlanVO projectPlanVO : projectPlanVOS) {
            if (projectPlanVO.getPkPlan().equals(projectPlanVO.getPkRoot())) {
                pkPlans.add(projectPlanVO.getPkPlan());
            }
        }
        if (pkPlans != null) {
            PlanWriteVO[] planWriteVOS = planWriteMapper.queryPlanByRootIds(pkPlans.toArray(new String[pkPlans.size()]));

            Map<String, ProjectPlanVO> projectPlanMap = new HashMap<>();
            for (ProjectPlanVO projectPlanVO : projectPlanVOS) {
                if (projectPlanMap.get(projectPlanVO.getPkPlan()) == null) {
                    projectPlanMap.put(projectPlanVO.getPkPlan(), projectPlanVO);
                }
            }
            for (PlanWriteVO planWriteVO : planWriteVOS) {
                ProjectPlanVO projectPlanVO = projectPlanMap.get(planWriteVO.getPkPlan());
                if (projectPlanVO != null && planWriteVO.getBillstatus() == BillStatusConst.COMMON_APPROVING_STATUS) {
                    projectPlanVO.setStatus(BillStatusConst.COMMON_APPROVING_STATUS);
                    projectPlanVO.setPkPlanwrite(planWriteVO.getPkPlanwrite());//查看审批记录时用到
                }
            }
        }
    }

    @Override
    public ProjectPlanViewVO[] queryViewLeafByRoot(String rootId) throws BusinessException {
        if (rootId == null) {
            throw new IllegalRequestArgException();
        }
        ProjectPlanVO[] leafPlans = mapper.queryLeafByRoot(rootId);
        return transAndFillViewVO(leafPlans);
    }

    @Override
    public PlanProgressHistoryVO[] queryProgressHisByPlan(String planId) throws BusinessException {
        PlanProgressHistoryVO[] histories = hisMapper.queryProgressHisByPlan(planId, null);
        if (!ArrayUtils.isEmpty(histories)) {
            //检测历史记录状态标识
            checkHistoryPlanStatus(histories);

            String[] ids = new String[histories.length];
            for (int i = 0; i < histories.length; i++) {
                ids[i] = histories[i].getPkProgressHis();
            }
            // 查询图片
            Map<String, List<String>> picsMap = picService.queryPicsByPkEntitys(ids);
            if (picsMap != null && !picsMap.isEmpty()) {
                for (PlanProgressHistoryVO history : histories) {
                    List<String> strings = picsMap.get(history.getPkProgressHis());
                    if (strings != null && !strings.isEmpty()) {
                        history.setPictures(strings.toArray(new String[0]));
                    } else {
                        history.setPictures(new String[0]);
                    }
                }
            }

            //查询指标记录
            Map<String, List<MeasureIndexHistoryVO>> measureIndexHisMap = measureIndexHisQuery.queryByPkProgressHiss(ids);

            if (measureIndexHisMap != null) {
                for (PlanProgressHistoryVO history : histories) {
                    List<MeasureIndexHistoryVO> measureIndexHistoryVOS = measureIndexHisMap.get(history.getPkProgressHis());
                    if (measureIndexHistoryVOS != null) {
                        history.setMeasureIndexHistoryVOS(measureIndexHistoryVOS.toArray(new MeasureIndexHistoryVO[measureIndexHistoryVOS.size()]));
                    }
                }
            }
        }
        return histories;
    }

    //检测计划历史记录的状态，补全状态标志
    private void checkHistoryPlanStatus(PlanProgressHistoryVO[] histories) {
        //Map<计划填报主键，计划历史记录对象>
        Map<String, PlanProgressHistoryVO> historyVOMap = new HashMap<>();
        if (ArrayUtils.isNotEmpty(histories)) {
            for (PlanProgressHistoryVO planProgressHistoryVO : histories) {
                historyVOMap.put(planProgressHistoryVO.getPkPlanwrite(), planProgressHistoryVO);
            }
        }
        if (historyVOMap.size() > 0) {
            Set<String> keySet = historyVOMap.keySet();
            if (keySet != null && keySet.size() > 0) {
                PlanWriteVO[] planWriteVOS = planWriteMapper.queryByPlanWriteIds(keySet.toArray(new String[0]));
                if (ArrayUtils.isNotEmpty(planWriteVOS)) {
                    for (PlanWriteVO planWriteVO : planWriteVOS) {
                        if (planWriteVO.getBillstatus() == BillStatusConst.COMMON_REJECT_STATUS) {
                            PlanProgressHistoryVO remove = historyVOMap.remove(planWriteVO.getPkPlanwrite());
                            remove.setSign(PlanProgressHisConst.PLAN_PROGRESS_HIS_INVALID);
                        }
                    }
                }
            }
            if (historyVOMap.size() > 0) {
                for (Map.Entry<String, PlanProgressHistoryVO> entry : historyVOMap.entrySet()) {
                    PlanProgressHistoryVO value = entry.getValue();
                    value.setSign(PlanProgressHisConst.PLAN_PROGRESS_HIS_EFFECTIVE);
                }
            }
        }
    }

    @Override
    public ProjectPlanViewVO[] queryPlanByTenantId(String tenantId) throws BusinessException {
        ProjectPlanVO[] planVOS = mapper.queryPlanByTenantId(tenantId);
        if (planVOS == null || planVOS.length == 0) {
            return new ProjectPlanViewVO[0];
        }
        return transAndFillViewVO(planVOS);
    }

    @Override
    public ProjectPlanViewVO[] queryLastViewByProject(String projectId) throws BusinessException {
        ProjectVO projectVO = projectMapper.getById(projectId);
        ProjectPlanVO[] allPlans = mapper.queryLastPlanByProject(projectId);
        if (ArrayUtils.isEmpty(allPlans)) {
            return null;
        }
        ProjectPlanViewVO[] plans = transAndFillViewVO(allPlans);
        for (ProjectPlanViewVO vo : plans) {
            vo.setProjectState(projectVO.getProjectState());
        }

        return plans;
    }

    @Override
    public Map<String, List<ProjectPlanViewVO>> queryLastViewByProjects(String[] projectIds) throws BusinessException {
        if (ArrayUtils.isEmpty(projectIds)) return new HashMap<>();

        Set<String> pkProjectSet = new HashSet<>();
        pkProjectSet.addAll(Arrays.asList(projectIds));
        ProjectVO[] projectVOS = projectMapper.queryVOByIds(BulkDataSplitUtils.getSplitDataSet(pkProjectSet));
        ProjectPlanVO[] allPlans = mapper.queryLastPlanByProjects(SqlUtil.getSqlIn(projectIds));
        if (ArrayUtils.isEmpty(allPlans)) {
            return null;
        }
        Map<String, ProjectVO> recordProject = new HashMap<>();
        if (ArrayUtils.isNotEmpty(projectVOS)) {
            for (ProjectVO vo : projectVOS) {
                if (vo != null && vo.getPkProject() != null) recordProject.put(vo.getPkProject(), vo);
            }
        }
        ProjectPlanViewVO[] plans = transAndFillViewVO(allPlans);

        Map<String, List<ProjectPlanViewVO>> resultMap = new HashMap<>();
        for (ProjectPlanViewVO vo : plans) {
            if (vo == null || vo.getPkProject() == null) continue;
            String pkProject = vo.getPkProject();
            if (resultMap.get(pkProject) == null) {
                resultMap.put(pkProject, new ArrayList<ProjectPlanViewVO>());
            }
            resultMap.get(pkProject).add(vo);
            if (recordProject.get(pkProject) != null) {
                vo.setProjectState(recordProject.get(pkProject).getProjectState());
            }
        }
        return resultMap;
    }

    @Override
    public ProjectPlanViewVO[] queryHistoryView(String planId) throws BusinessException {






        ProjectPlanVO planVO = mapper.getById(planId);
        ProjectPlanVO[] hisVOS = mapper.queryhistoryPlan(planVO.getPkSrc());
        ProjectPlanViewVO[] plans = transAndFillViewVO(hisVOS);
        return plans;
    }

    private ProjectPlanViewVO[] transAndFillViewVO(ProjectPlanVO[] allPlans) throws BusinessException {
        List<String> leavesId = new ArrayList<>(allPlans.length);
        Set<String> projectIdSet = new HashSet<>();
        List<String> pkPlanList = new ArrayList<>();
        Set<String> pkMilestoneSet = new HashSet<>();
        for (ProjectPlanVO plan : allPlans) {
            projectIdSet.add(plan.getPkProject());
            if (plan.getChildCount() == 0) {
                leavesId.add(plan.getPkPlan());
            }

            if (StringUtils.isNotEmpty(plan.getPkMilestone()))
                pkMilestoneSet.add(plan.getPkMilestone());

            pkPlanList.add(plan.getPkPlan());
        }

        List<FailedExternalRecordVO> recordVOS = recordQuery.queryByPkBills(pkPlanList);
        Map<String, String> recordVOMap = null;
        if (recordVOS != null && recordVOS.size() > 0) {
            recordVOMap = new HashMap<>();
            for (FailedExternalRecordVO recordVO : recordVOS) {
                recordVOMap.put(recordVO.getRelateKey(), recordVO.getPkFailedExternalRecord());
            }
        }


        ProjectVO[] projectVos = projectMapper.queryVOByIds(BulkDataSplitUtils.getSplitDataSet(projectIdSet));
        Map<String, ProjectVO> projectIdMap = new HashMap<>();
        if (!ArrayUtils.isEmpty(projectVos)) {
            for (ProjectVO projectVo : projectVos) {
                projectIdMap.put(projectVo.getPkProject(), projectVo);
            }
        }

        PlanProgressVO[] progressVOs = null;
        if(leavesId != null && !leavesId.isEmpty()){
            progressVOs = progMapper.queryByPlanIds(leavesId.toArray(new String[0]));
        }
        Map<String, PlanProgressVO> idProgressMap = new HashMap<>();
        if (!ArrayUtils.isEmpty(progressVOs)) {
            for (PlanProgressVO prog : progressVOs) {
                idProgressMap.put(prog.getPkPlan(), prog);
            }
        }

        Map<String, String> milestoneMap = null;
        if (pkMilestoneSet.size() > 0) {
            // 查询里程碑名称
            milestoneMap = milestoneQuery.queryNameById(pkMilestoneSet.toArray(new String[0]));
        }

        // 转换并设置数据
        ProjectPlanViewVO[] plans = new ProjectPlanViewVO[allPlans.length];
        for (int i = 0; i < plans.length; i++) {
            plans[i] = ProjectPlanViewVO.convertVO(allPlans[i]);
            PlanProgressVO planProgressVO = idProgressMap.get(plans[i].getPkPlan());
            if (planProgressVO != null) {
                plans[i].setProgress(planProgressVO.getProgress());
                plans[i].setStartDate(planProgressVO.getStartDate());
                plans[i].setEndDate(planProgressVO.getEndDate());
                plans[i].setFirstSubmitDate(planProgressVO.getFirstSubmitDate());
                plans[i].setLastSubmitDate(planProgressVO.getLastSubmitDate());
            }
            ProjectVO projectVO = projectIdMap.get(plans[i].getPkProject());
            if (projectVO != null) {
                plans[i].setProjectCode(projectVO.getScode());
                plans[i].setProjectName(projectVO.getSname());
                plans[i].setProjectManager(projectVO.getManager());
                plans[i].setIsKey(projectVO.getIskey());
                plans[i].setPkOrg(projectVO.getPkOrg());
            }

            if (recordVOMap != null && StringUtils.isNotEmpty(recordVOMap.get(plans[i].getPkPlan()))) {
                plans[i].setFailedCommit("[" + plans[i].getSname() + "]计划提交失败，请重新点击提交！");
            }

            // 设置里程碑名称
            if (milestoneMap != null && StringUtils.isNotEmpty(plans[i].getPkMilestone()))
                plans[i].setMilestoneName(milestoneMap.get(plans[i].getPkMilestone()));
        }

        return plans;
    }

    /**
     * 统计项目的，总进度
     */
    @Override
    public Map<String, Integer> getTotalProgress(String[] pkProjects) throws BusinessException {
        // TODO 这部分效率可能存在极大问题
        Map<String, List<ProjectPlanViewVO>> projectPlanMap = queryLastViewByProjects(pkProjects);
        if (projectPlanMap == null) return new HashMap<>();

        for (String key : projectPlanMap.keySet()) {  //用double表示，最终需求要求每层都向下取整，其实没必要用double了
            if (projectPlanMap.get(key) != null) {
                for (ProjectPlanViewVO vo : projectPlanMap.get(key)) {
                    if (vo != null && vo.getProgress() != null) vo.setDoubleProgress((double) vo.getProgress());
                }
            }
        }
        Map<String, Integer> result = new HashMap<>();

        for (String key : projectPlanMap.keySet()) {
            if (projectPlanMap.get(key) == null || projectPlanMap.get(key).size() == 0) continue;
            Map<String, List<ProjectPlanViewVO>> childMap = genChildMap(projectPlanMap.get(key));
            List<ProjectPlanViewVO> rootVOS = childMap.get(StringUtils.EMPTY);
            if (rootVOS == null) {
                result.put(key, 0);
            } else {
                ProjectPlanViewVO parent = new ProjectPlanViewVO();
                calProgress(parent, rootVOS, childMap);
                result.put(key, parent.getDoubleProgress().intValue());
            }
        }

        return result;
    }

    @Override
    public ProjectPlanViewVO[] getPlanWriteById(String pkPlanWrite) throws BusinessException {
        PlanWriteVO planWriteVO = planWriteMapper.queryBypkPlanWrite(pkPlanWrite);
        //获取根节点以及所有子节点
        ProjectPlanVO[] projectPlanVOS = mapper.queryPlanByRoot(planWriteVO.getPkPlan());

        //过滤没有修改的子节点
        PlanProgressHistoryVO[] planProgressHistoryVOS = hisMapper.queryProgressHistoryByPkPlanWrite(pkPlanWrite);
        Map<String, PlanProgressHistoryVO> planProgressHistoryVOMap = new HashMap<>();
        if (planProgressHistoryVOS != null) {
            for (PlanProgressHistoryVO progressHistoryVO : planProgressHistoryVOS) {
                if (planProgressHistoryVOMap.get(progressHistoryVO.getPkPlan()) == null) {
                    planProgressHistoryVOMap.put(progressHistoryVO.getPkPlan(), progressHistoryVO);
                }
            }
        }

        if (projectPlanVOS != null) {
            for (ProjectPlanVO projectPlanVO : projectPlanVOS) {
                if (planProgressHistoryVOMap.get(projectPlanVO.getPkPlan()) == null) {
                    projectPlanVO.setMark(PlanProgressMarkConst.MARK_NO_SHOW);
                } else {
                    projectPlanVO.setMark(PlanProgressMarkConst.MARK_SHOW);
                }
            }
        }

        for (ProjectPlanVO projectPlanVO : projectPlanVOS) {
            projectPlanVO.setPkPlanwrite(planWriteVO.getPkPlanwrite());
        }
        //检验项目下根计划是否是审批中
        checkRootPlan(projectPlanVOS);

        ProjectPlanViewVO[] projectPlanViewVOS = transToViewVO(projectPlanVOS);
        return projectPlanViewVOS;
    }

    @Override
    public ProjectPlanVO[] queryByProjectAndRelatedBillType(String pkProject, String billType, String transiType) {
        List<String> billTypes = new ArrayList<>();
        billTypes.add(billType);
        // 交易类型不为空，查询关联了单据类型或交易类型的计划
        if (StringUtils.isNotEmpty(transiType)) {
            billTypes.add(transiType);
        }

        return mapper.queryByProjectAndRelatedBillType(pkProject, billTypes);
    }

    @Override
    public PlanProgressVO[] queryProgressByPlans(String[] pkPlans) {
        if (ArrayUtils.isEmpty(pkPlans))
            return new PlanProgressVO[0];

        return progMapper.queryByPlanIds(pkPlans);
    }

    @Override
    public Map<String, List<ProjectPlanVO>> queryChildPlanByParents(String[] pkParents) {
        ProjectPlanVO[] planVOS = mapper.queryChildPlanByParents(pkParents);
        if (ArrayUtils.isEmpty(planVOS))
            return new HashMap<>(0);

        Map<String, List<ProjectPlanVO>> result = new HashMap<>();
        String pkParent;
        for (ProjectPlanVO vo : planVOS) {
            pkParent = vo.getPkParent();
            if (!result.containsKey(pkParent))
                result.put(pkParent, new ArrayList<ProjectPlanVO>());

            result.get(pkParent).add(vo);
        }

        return result;
    }

    @Override
    public List<ProjectPlanVO> queryByPkPlans(String[] pkPlans) {
        if (ArrayUtils.isEmpty(pkPlans))
            return new ArrayList<>(0);

        return mapper.queryByPkPlans(pkPlans);
    }

    @Override
    public List<ProjectPlanVO> queryByProjectAndDependPlan(String pkProject, String[] dependPlans) {
        if (StringUtils.isEmpty(pkProject) || ArrayUtils.isEmpty(dependPlans))
            return new ArrayList<>(0);

        return mapper.queryByProjectAndDependPlan(pkProject, dependPlans);
    }

    @Override
    public ProjectPlanViewVO queryViewByPkPlan(String pkPlan) throws BusinessException {
        //通过pkPlan 获取 projectPlan
        ProjectPlanVO projectPlanVO = mapper.queryByPkPlan(pkPlan);

        // 翻译前置计划
        if (projectPlanVO != null && projectPlanVO.getDependPlan() != null) {
            ProjectPlanVO dependPlan = mapper.getById(projectPlanVO.getDependPlan());
            if (dependPlan != null) {
                projectPlanVO.setDependPlanName(dependPlan.getSname());
            }
        }

        if(projectPlanVO != null) {
            //做数据转换
            ProjectPlanViewVO[] projectPlanViewVOS = transAndFillViewVO(new ProjectPlanVO[]{projectPlanVO});

            ProjectPlanViewVO projectPlanViewVO = projectPlanViewVOS[0];
            //填充反馈信息及指标记录

            PlanProgressHistoryVO[] planProgressHistoryVOS = hisMapper.queryLastProgressHistoryByPkPlans(new String[]{pkPlan});

            MeasureIndexHistoryVO[] measureIndexHistoryVOS = null;
            PlanProgressHistoryVO planProgressHistoryVO = null;
            if(planProgressHistoryVOS != null && planProgressHistoryVOS.length != 0){
                planProgressHistoryVO = planProgressHistoryVOS[0];
                String pkProgressHis = planProgressHistoryVO.getPkProgressHis();

                //通过反馈记录主键查询指标记录
                measureIndexHistoryVOS = measureIndexHisMapper.selectMeasureIndexVOByProgressHis(pkProgressHis);
            }
            //如果是第一次反馈没有指标记录 则查计划指标项
            if(measureIndexHistoryVOS == null || measureIndexHistoryVOS.length==0){
                List<PlanIndexVO> planIndexVOS = planIndexQuery.queryIndexOfPlan(pkPlan);
                if(planIndexVOS != null || !planIndexVOS.isEmpty()) {
                    MeasureIndexHistoryVO[] vos = new MeasureIndexHistoryVO[planIndexVOS.size()];
                    //数据转换
                    for (int i=0; i<planIndexVOS.size(); i++) {
                        MeasureIndexHistoryVO vo = new MeasureIndexHistoryVO();
                        PlanIndexVO planIndexVO = planIndexVOS.get(i);
                        vo.setPkPlanIndex(planIndexVO.getPkPlanIndex());
                        vo.setExpectTotal(planIndexVO.getExpectTotal());
                        vo.setMeasureIndexName(planIndexVO.getName());
                        vo.setUnit(planIndexVO.getUnit());
                        vo.setPkMeasureindex(planIndexVO.getPkMeasureIndex());
                        vos[i] = vo;
                    }
                    measureIndexHistoryVOS = vos;
                }
            }
            projectPlanViewVO.setDescription(planProgressHistoryVO == null ? "" : planProgressHistoryVO.getDescription());
            projectPlanViewVO.setMeasureIndexHistoryVOS(measureIndexHistoryVOS);
            return projectPlanViewVO;
        }

        return null;
    }

    @Override
    public ProjectPlanViewVO[] queryMilltStonePlanByPkProject(String pkProject,String pkPlan) throws BusinessException {
        ProjectPlanVO[] projectPlanVOS = mapper.queryMillStonePlanById(pkProject,pkPlan);
        if(projectPlanVOS != null && projectPlanVOS.length != 0){
            ProjectPlanViewVO[] projectPlanViewVOS = transAndFillViewVO(projectPlanVOS);

            //设置里程碑状态 及 是否延期
            if(projectPlanViewVOS != null) {
                for (ProjectPlanViewVO projectPlanViewVO : projectPlanViewVOS) {
                    if (projectPlanViewVO.getProgress() == 0)
                        projectPlanViewVO.setMilestoneStatus(MillStoneStatusConst.NOT_START);
                    if (0 < projectPlanViewVO.getProgress() && projectPlanViewVO.getProgress() < 100)
                        projectPlanViewVO.setMilestoneStatus(MillStoneStatusConst.IN_PROGRESS);
                    if (projectPlanViewVO.getProgress() == 100)
                        projectPlanViewVO.setMilestoneStatus(MillStoneStatusConst.END);

                    String milestoneStatus = projectPlanViewVO.getMilestoneStatus();

                    /**
                     *   未开始：当前日期>计划开始日期;
                     *   进行中：当前日期>计划完成日期;
                     *   已完成：实际完成日期>计划完成日期；
                     */
                    boolean flag = false;
                    Date now = new Date();
                    if(MillStoneStatusConst.NOT_START.equals(milestoneStatus)){
                        flag = compareDateIngoreHMS(now,projectPlanViewVO.getExpeStartDate());
                    }
                    if(MillStoneStatusConst.IN_PROGRESS.equals(milestoneStatus)){
                        flag = compareDateIngoreHMS(now,projectPlanViewVO.getExpeEndDate());
                    }
                    if(MillStoneStatusConst.END.equals(milestoneStatus)){
                        flag = projectPlanViewVO.getEndDate().after(projectPlanViewVO.getExpeEndDate());
                    }
                    projectPlanViewVO.setIsExtension(flag);
                    String billType = projectPlanViewVO.getRelatedBillType();

                    if(!StringUtils.isEmpty(billType)) {
                        if(!billType.equalsIgnoreCase(BillTypeConst.WORKSTART_BILLTYPE) && !billType.equalsIgnoreCase(BillTypeConst.COMPREHENSIVE_ACCEPTANCE_BILLTYPE)) {
                            projectPlanViewVO.setIsNcBill(true);
                        }
                    }
                }

            }

            return projectPlanViewVOS;
        }
        return null;
    }

    private ProjectPlanViewVO[] transToViewVO(ProjectPlanVO[] allPlans) throws BusinessException {
        List<String> leavesId = new ArrayList<>(allPlans.length);
        Set<String> projectIdSet = new HashSet<>();
        List<String> pkPlanList = new ArrayList<>();
        //Map反馈历史
        Map<String, PlanProgressHistoryVO> historyVOMap = new HashMap<>();
        for (ProjectPlanVO plan : allPlans) {
            projectIdSet.add(plan.getPkProject());
            if (plan.getChildCount() == 0) {
                //根据子叶子节点查询实际开始时间以及描述和图片信息
                PlanProgressHistoryVO[] planProgressHistoryVOS = hisMapper.queryProgressHisByPlan(plan.getPkPlan(), plan.getPkPlanwrite());
                if (ArrayUtils.isNotEmpty(planProgressHistoryVOS)) {
                    historyVOMap.put(planProgressHistoryVOS[0].getPkPlan(), planProgressHistoryVOS[0]);
                }

                leavesId.add(plan.getPkPlan());
            }
            pkPlanList.add(plan.getPkPlan());
        }

        List<FailedExternalRecordVO> recordVOS = recordQuery.queryByPkBills(pkPlanList);
        Map<String, String> recordVOMap = null;
        if (recordVOS != null && recordVOS.size() > 0) {
            recordVOMap = new HashMap<>();
            for (FailedExternalRecordVO recordVO : recordVOS) {
                recordVOMap.put(recordVO.getRelateKey(), recordVO.getPkFailedExternalRecord());
            }
        }

        ProjectVO[] projectVos = projectMapper.queryVOByIds(BulkDataSplitUtils.getSplitDataSet(projectIdSet));
        Map<String, ProjectVO> projectIdMap = new HashMap<>();
        if (!ArrayUtils.isEmpty(projectVos)) {
            for (ProjectVO projectVo : projectVos) {
                projectIdMap.put(projectVo.getPkProject(), projectVo);
            }
        }

        PlanProgressVO[] progressVOs = progMapper.queryByPlanIds(leavesId.toArray(new String[0]));
        Map<String, PlanProgressVO> idProgressMap = new HashMap<>();
        if (!ArrayUtils.isEmpty(progressVOs)) {
            for (PlanProgressVO prog : progressVOs) {
                idProgressMap.put(prog.getPkPlan(), prog);
            }
        }
        // 转换并设置数据
        ProjectPlanViewVO[] plans = new ProjectPlanViewVO[allPlans.length];
        for (int i = 0; i < plans.length; i++) {
            plans[i] = ProjectPlanViewVO.convertVO(allPlans[i]);
            PlanProgressVO planProgressVO = idProgressMap.get(plans[i].getPkPlan());
            //字段赋值
            PlanProgressHistoryVO planProgressHistoryVO = historyVOMap.get(plans[i].getPkPlan());
            if (planProgressHistoryVO != null) {
                String[] pictures = picService.queryPicNamesByPkEntity(planProgressHistoryVO.getPkProgressHis());
                if (planProgressHistoryVO != null) {
                    plans[i].setExecuteStartDate(planProgressHistoryVO.getStartDate());
                    plans[i].setExecuteEndDate(planProgressHistoryVO.getEndDate());
                    plans[i].setDescription(planProgressHistoryVO.getDescription());
                    plans[i].setPictures(pictures);
                }
            }
            if (planProgressVO != null) {
                plans[i].setProgress(planProgressVO.getProgress());
                plans[i].setStartDate(planProgressVO.getStartDate());
                plans[i].setEndDate(planProgressVO.getEndDate());
                plans[i].setFirstSubmitDate(planProgressVO.getFirstSubmitDate());
                plans[i].setLastSubmitDate(planProgressVO.getLastSubmitDate());
            }

            ProjectVO projectVO = projectIdMap.get(plans[i].getPkProject());
            if (projectVO != null) {
                plans[i].setProjectCode(projectVO.getScode());
                plans[i].setProjectName(projectVO.getSname());
                plans[i].setProjectManager(projectVO.getManager());
                plans[i].setIsKey(projectVO.getIskey());
                plans[i].setPkOrg(projectVO.getPkOrg());
            }

            if (recordVOMap != null && StringUtils.isNotEmpty(recordVOMap.get(plans[i].getPkPlan()))) {
                plans[i].setFailedCommit("[" + plans[i].getSname() + "]计划提交失败，请重新点击提交！");
            }

        }
        return plans;
    }

    /**
     * 构造树
     */
    private Map<String, List<ProjectPlanViewVO>> genChildMap(List<ProjectPlanViewVO> allVOs) {
        // 构造树
        Map<String, List<ProjectPlanViewVO>> childMap = new HashMap<>();
        for (ProjectPlanViewVO vo : allVOs) {
            vo.setKey(vo.getPkPlan());
            String parent = vo.getPkParent();
            if (StringUtils.isEmpty(parent)) {
                parent = StringUtils.EMPTY;
            }
            List<ProjectPlanViewVO> children = childMap.get(parent);
            if (children == null) {
                children = new ArrayList<>();
                childMap.put(parent, children);
            }
            children.add(vo);
        }
        for (ProjectPlanViewVO vo : allVOs) {
            vo.setScode(null);
        }
        for (ProjectPlanViewVO vo : allVOs) {
            List<ProjectPlanViewVO> children = childMap.get(vo.getPkPlan());
            if (children != null) {
                vo.setChildren(children.toArray(new ProjectPlanViewVO[0]));
            }
        }
        return childMap;
    }

    /**
     * 计算总进度
     */
    private void calProgress(ProjectPlanViewVO parent, List<ProjectPlanViewVO> rootVOS, Map<String, List<ProjectPlanViewVO>> childMap) {
        double sumProgress = 0, sumExpeDuration = 0;
        for (ProjectPlanViewVO plan : rootVOS) {
            List<ProjectPlanViewVO> children = childMap.get(plan.getPkPlan());
            if (children != null && !children.isEmpty()) {
                calProgress(plan, children, childMap);
            }
            sumProgress += (plan.getDoubleProgress() == null ? 0 : plan.getDoubleProgress()) * plan.getExpeDuration();
            sumExpeDuration += (double) plan.getExpeDuration();
        }
        parent.setDoubleProgress(sumExpeDuration < 0.1 ? 0 : Math.floor(sumProgress / sumExpeDuration));
    }

    public boolean compareDateIngoreHMS(Date date,Date targetDate){
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date);
        // 将时分秒,毫秒域清零
        cal1.set(Calendar.HOUR_OF_DAY, 0);
        cal1.set(Calendar.MINUTE, 0);
        cal1.set(Calendar.SECOND, 0);
        cal1.set(Calendar.MILLISECOND, 0);
        return cal1.after(targetDate);
    }

}
